package future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Demo1 {

    //异步调用CompletableFuture
    //异步执行
    //成功回调
    //失败回调
    public static void main(String[] args) {
        //发起请求
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"---ThreadSleep:2");
//        });
//
//        System.out.println("-------");
//
//        Void unused = completableFuture.get();
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"---supplyAsync:Integer");
            int i = 10/0;
            return 2048;
        });

        Integer integer = null;
        try {
            integer = completableFuture.whenComplete((a1, a2) -> {
                System.out.println("a1->" + a1);//第一个参数：正常返回结果
                System.out.println("a2->" + a2);//第二个参数：错误返回结果
            }).exceptionally((e) -> {
                System.out.println(e.getMessage());
                return 40000;
            }).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println(integer);
    }
}
